﻿using System;
using System.Security.Principal;
using System.Web;
using Bricks.Injecting;
using Bricks.Security;

namespace Motar.Web.Mvc
{

    /// <summary>
    /// 
    /// </summary>
    public class AuthorizeAttribute : AuthorizeAttributeBase
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="authorizationFacadeResolver"></param>
        public AuthorizeAttribute(IValueResolver<IAuthorizationFacade> authorizationFacadeResolver)
        {
            if (authorizationFacadeResolver == null)
            {
                throw new ArgumentNullException("authorizationFacadeResolver");
            }
            _authorizationFacadeResolver = authorizationFacadeResolver;
        }

        /// <summary>
        /// 
        /// </summary>
        public AuthorizeAttribute() :
            this(new SingleValueResolver<IAuthorizationFacade>())
        {
        }

        /// <summary>
        /// 
        /// </summary>
        private readonly IValueResolver<IAuthorizationFacade> _authorizationFacadeResolver;

        /// <summary>
        /// 
        /// </summary>
        protected IValueResolver<IAuthorizationFacade> AuthorizationFacadeResolver
        {
            get { return _authorizationFacadeResolver; }
        }

        /// <summary>
        /// 
        /// </summary>
        public virtual string Key { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        protected override bool Authorize(HttpContextBase httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }

            IPrincipal principal = httpContext.User;

            if (!principal.Identity.IsAuthenticated)
            {
                return false;
            }

            return string.IsNullOrEmpty(Key) ? true : AuthorizationFacadeResolver.Resolve().Authorize(principal, Key);
        }
    }
}
